package com.xie.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xie.common.utils.PageUtils;
import com.xie.common.utils.Query;
import com.xie.gulimall.product.dao.CategoryDao;
import com.xie.gulimall.product.entity.CategoryEntity;
import com.xie.gulimall.product.service.CategoryBrandRelationService;
import com.xie.gulimall.product.service.CategoryService;
import com.xie.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author xiefeixiang
 */ // TODO: 2020/5/29 需要整理，分布式情况
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    //    @Autowired
//    private CategoryDao categoryDao;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出多有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2.组装成父子的树形结构
        // 2.1.先找到一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenu(List<Long> asList) {
        // TODO: 2020/4/11 检查当前菜单是否被引用

        // 逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新数据
     *
     * @param category
     */

    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    // 代表当前方法的结果需要缓存，如果缓存中有，方法不用调用，如果缓存中个没有，会调用方法，最后将结果放入到缓存
    //每个需要缓存的数据我们都来制定要放入的那个名字的缓存，缓存的分区按照业务区分
    // ttl 在配置文件中
    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Category() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }


    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        // 加入缓存，对象转为json格式放入，json拿出来转为对象
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 缓存没有数据
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithLocalLock();

            return catalogJsonFromDb;
        }
        // 转对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    /**
     * 正确的做法，使用redisson
     * 缓存数据的一致性问题：
     * 1.双写模式
     * 2.失效模式
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        //占分布式锁 注意锁名，锁的粒度，越细越快
        // 锁的粒度 具体缓存的是某个数据，11号商品 product-11-lock
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> catalogJsonFromDbWithLocalLock;
        try {
            catalogJsonFromDbWithLocalLock = getCatalogJsonFromDbWithLocalLock();
        } finally {
            lock.unlock();
        }
        return catalogJsonFromDbWithLocalLock;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        //分布式锁
        String uuid = UUID.randomUUID().toString();
        //创建分布式锁方法，必须同时加过期时间
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功,执行业务
            // 设置过期时间
            //必须原子性
            //获取锁成功，查询数据库，并且放入缓存
            // TODO: 2020/5/28 提取方法
//            stringRedisTemplate.expire("lock", 30, TimeUnit.SECONDS);
            Map<String, List<Catelog2Vo>> catalogJsonFromDbWithLocalLock;
            try {
                catalogJsonFromDbWithLocalLock = getCatalogJsonFromDbWithLocalLock();
            } finally {
                // 删除锁
//            stringRedisTemplate.delete("lock"); 删除的锁是别人的
                //删除锁必须是原子操作
            /*String lockValue = stringRedisTemplate.opsForValue().get("lock");
            if(uuid.equals(lockValue)){
                //删除自己的锁
                stringRedisTemplate.delete("lock");
            }*/
                // lua脚本解锁
                String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                // redis删除成功返回Integer的1，否则为0
                Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return catalogJsonFromDbWithLocalLock;
        } else {
            // 加锁失败，重试，自旋状态，调用方法
            // 休眠
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            getCatalogJsonFromDbWithRedisLock();
        }
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            // 缓存不为空
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        /**
         * 1,将数据库的多次查询变为一次,提升性能
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> level1Category = getParentCid(selectList, 0L);
        //封装数据
        Map<String, List<Catelog2Vo>> catelogMap = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    //查询一级分类对应的二级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
                    //封装结果
                    List<Catelog2Vo> catelog2Vo2 = null;
                    if (categoryEntities != null && categoryEntities.size() > 0) {
                        catelog2Vo2 = categoryEntities.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            // 找当前二级分类的三级分类封装成vo
                            List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                            if (level3Catelog != null && level1Category.size() > 0) {
                                //封装成三级的vo
                                List<Catelog2Vo.Catelog3Vo> level3Collect = level3Catelog.stream().map(l3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(level3Collect);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }

                    return catelog2Vo2;
                }
        ));

        return catelogMap;
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {

        // synchronized (this){ 再springboot中所有组件在容器中都是单例的
        synchronized (this) {
            //得到锁以后，我们应该再去缓存中确定一次，如果没有再查数据
            String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJson");
            if (!StringUtils.isEmpty(catalogJSON)) {
                // 缓存不为空
                Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
                return result;
            }
            /**
             * 1,将数据库的多次查询变为一次,提升性能
             */
            List<CategoryEntity> selectList = baseMapper.selectList(null);

            //查出所有1级分类
            List<CategoryEntity> level1Category = getParentCid(selectList, 0L);
            //封装数据
            Map<String, List<Catelog2Vo>> catelogMap = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                        //查询一级分类对应的二级分类
                        List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
                        //封装结果
                        List<Catelog2Vo> catelog2Vo2 = null;
                        if (categoryEntities != null && categoryEntities.size() > 0) {
                            catelog2Vo2 = categoryEntities.stream().map(l2 -> {
                                Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                // 找当前二级分类的三级分类封装成vo
                                List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                                if (level3Catelog != null && level1Category.size() > 0) {
                                    //封装成三级的vo
                                    List<Catelog2Vo.Catelog3Vo> level3Collect = level3Catelog.stream().map(l3 -> {
                                        Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                        return catelog3Vo;
                                    }).collect(Collectors.toList());
                                    catelog2Vo.setCatalog3List(level3Collect);
                                }
                                return catelog2Vo;
                            }).collect(Collectors.toList());
                        }


                        return catelog2Vo2;
                    }
            ));
            //放入缓存,将对象转为json字符串
            String s = JSON.toJSONString(catelogMap);
            stringRedisTemplate.opsForValue().set("catalogJson", s);

            return catelogMap;
        }
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parent_cid) {
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item ->
                item.getParentCid().equals(parent_cid)
        ).collect(Collectors.toList());
        return collect;
    }

    /**
     * 收集路径
     *
     * @return
     */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        // 1.收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root
     * @param allEntityList
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> allEntityList) {
        List<CategoryEntity> collect = allEntityList.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            // 找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, allEntityList));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            // 菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }
}

